<template>
  <div>
    <NavBar />
    <div class="post-container">
      <!-- 帖子信息展示 -->
      <el-card class="post-card" v-if="post">
        <img :src="getCoverImage(post.id)" class="post-cover" alt="Post Cover" />
        <h2>{{ post.title }}</h2>
        <div class="post-meta">
          <span
            class="author-link"
            @click="openMessageDialog"
            @mouseover="isAuthorLinkHovered = true"
            @mouseleave="isAuthorLinkHovered = false"
          >作者: {{ post.authorUsername }}</span>
          <span>发布时间: {{ formatDate(post.createdAt) }}</span>
        </div>
        <p>{{ post.content }}</p>
        <!-- 标签展示 -->
        <div class="post-tags" v-if="post.tags && post.tags.length">
          <span v-for="tag in post.tags" :key="tag" class="post-tag">
            <el-link :href="'#' + tag">#{{ tag }}</el-link>
          </span>
        </div>
        <!-- 分类展示 -->
        <div class="post-category" v-if="post.category">
          <span>分类: {{ post.category.name }}</span>
        </div>
      </el-card>

      <!-- 资源信息展示 -->
      <div class="resource-section" v-if="post && post.resourceFileName">
        <h3>资源</h3>
        <el-card class="resource-card">
          <el-link @click.prevent="fetchResource(post.resourceId, post.resourceFileName)">{{ post.resourceFileName }}</el-link>
          <p>{{ post.resourceDescription }}</p>
        </el-card>
      </div>

      <!-- 评论展示 -->
      <div class="comments-section">
        <h3>评论</h3>
        <el-card v-for="comment in nestedComments" :key="comment.id" class="comment-card">
          <div class="comment-meta">
            <span>{{ comment.username }}</span>
            <span>{{ formatDate(comment.createdAt) }}</span>
          </div>
          <p @click="openReplyDialog(comment)">
            <span class="comment-content">{{ comment.content }}</span>
          </p>
          <div v-if="comment.children && comment.children.length" class="comment-children">
            <el-card v-for="child in comment.children" :key="child.id" class="comment-card">
              <div class="comment-meta">
                <span>{{ child.username }}</span>
                <span>{{ formatDate(child.createdAt) }}</span>
              </div>
              <p @click="openReplyDialog(child)">
                <span class="comment-content">{{ child.content }}</span>
              </p>
            </el-card>
          </div>
        </el-card>
        <div v-if="!comments.length">
          <p>暂无评论</p>
        </div>
        <!-- 立即评论按钮 -->
        <div class="comment-button">
          <el-button type="primary" @click="openReplyDialog(null)">立即评论</el-button>
        </div>
      </div>
    </div>

    <!-- 回复评论对话框 -->
    <el-dialog v-model="replyDialogVisible" title="评论 / 留言" :style="{ width: '50%' }">
      <el-input type="textarea" v-model="replyContent" placeholder="请输入回复内容"></el-input>
      <template #footer>
        <el-button @click="replyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReply">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from '../plugins/axios'
import NavBar from '../components/NavBar.vue'

const store = useStore()
const route = useRoute()

const post = ref(null)
const comments = ref([])
const replyDialogVisible = ref(false)
const replyContent = ref('')
const currentComment = ref(null)
const isAuthorLinkHovered = ref(false)
const isMessageMode = ref(false)

const coverImageCount = ref(20)

// 获取封面图片 URL 的方法
const getCoverImage = (postId: number) => {
  const imageIndex = (postId % coverImageCount.value) + 1;
  return `/covers/${imageIndex}.jpg`;
}

// 格式化日期
const formatDate = (dateString: string) => {
  const options: Intl.DateTimeFormatOptions = {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  }
  return new Date(dateString).toLocaleDateString('zh-CN', options)
}

const fetchResource = async (resourceId: string, resourceFileName: string) => {
  try {
    const response = await axios.get(`/resources/${resourceId}`, {
      responseType: 'blob' // 设置响应类型为 blob
    })
    if (response.status === 200) {
      const url = window.URL.createObjectURL(new Blob([response.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', resourceFileName) // 设置下载文件的文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    } else {
      ElMessage.error('资源获取失败')
    }
  } catch (error) {
    ElMessage.error('资源获取失败')
    console.error('Error fetching resource:', error)
  }
}

// 获取帖子数据
const fetchPost = async (postId: string) => {
  try {
    const response = await axios.get(`/posts/${postId}`)
    post.value = response.data
  } catch (error) {
    console.error('Failed to fetch post:', error)
  }
}

// 获取评论数据
const fetchComments = async (postId: string) => {
  try {
    const response = await axios.get(`/comments/${postId}`)
    comments.value = Array.isArray(response.data) ? response.data : []
  } catch (error) {
    console.error('Failed to fetch comments:', error)
  }
}

// 提交回复评论或留言
const submitReply = async () => {
  if (!replyContent.value) return

  try {
    const user = store.getters.getUser
    if (!user || !user.id) {
      console.error('User ID is not available')
      return
    }

    const payload = {
      postId: isMessageMode.value ? null : post.value.id,
      content: replyContent.value,
      userId: user.id, // 动态获取当前用户ID
      parentId: currentComment.value ? currentComment.value.id : null // 如果是一级评论，则 parentId 为 null
    }

    const url = isMessageMode.value ? '/messages' : '/comments'
    const response = await axios.post(url, payload)

    if (!isMessageMode.value) {
      fetchComments(post.value.id) // 重新获取评论以更新评论列表
    }

    replyDialogVisible.value = false
    replyContent.value = ''
    currentComment.value = null
    isMessageMode.value = false
  } catch (error) {
    console.error('Failed to submit reply or message:', error)
  }
}

// 打开回复评论对话框或留言对话框
const openReplyDialog = (comment) => {
  currentComment.value = comment
  replyContent.value = ''
  replyDialogVisible.value = true
  isMessageMode.value = false
}

// 打开留言对话框
const openMessageDialog = () => {
  currentComment.value = null
  replyContent.value = ''
  replyDialogVisible.value = true
  isMessageMode.value = true
}

// 处理嵌套评论
const nestedComments = computed(() => {
  const commentMap = new Map()
  comments.value.forEach(comment => {
    comment.children = []
    commentMap.set(comment.id, comment)
  })
  comments.value.forEach(comment => {
    if (comment.parentId !== null) {
      commentMap.get(comment.parentId).children.push(comment)
    }
  })
  return comments.value.filter(comment => comment.parentId === null)
})

onMounted(() => {
  const postId = route.params.id
  fetchPost(postId)
  fetchComments(postId)
})

</script>

<style scoped>
.post-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.post-card, .comment-card, .resource-card {
  margin: 10px 0;
}

.post-cover {
  width: 100%;
  height: auto; /* 保持图片的宽高比 */
  object-fit: cover; /* 确保图片覆盖整个容器 */
  margin-bottom: 10px; /* 图片与内容之间的间距 */
}

.post-meta, .comment-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.comment-children {
  margin-left: 20px;
}

.resource-section, .comments-section {
  margin-top: 20px;
}

.post-tags {
  margin-top: 10px;
}

.post-tag {
  margin-right: 10px;
}

.post-category {
  margin-top: 15px;
  font-weight: normal;
}

.comment-content {
  cursor: pointer;
  color: inherit;
  text-decoration: none;
}

.comment-content:hover {
  text-decoration: underline;
}

.comment-button {
  text-align: center;
  margin-top: 20px;
}

.author-link {
  cursor: pointer;
  color: inherit;
  text-decoration: none;
}

.author-link:hover {
  text-decoration: underline;
}
</style>